package com.lanvideo.config;

import com.lanvideo.entity.User;
import com.lanvideo.service.SessionService;
import com.lanvideo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private SessionService sessionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        
        // 如果没有会话，直接放行（让其他逻辑处理）
        if (session == null) {
            return true;
        }

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return true;
        }

        // 检查用户状态
        User currentUser = userService.getUserById(user.getId());
        if (currentUser == null || currentUser.getStatus() == null || currentUser.getStatus() == 0) {
            // 用户被禁用，强制退出
            sessionService.onUserLogout(session);
            session.invalidate();
            
            // 如果是API请求，返回JSON错误
            if (request.getRequestURI().startsWith("/api/")) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"账户已被禁用，请联系管理员\"}");
                return false;
            }
            
            // 如果是页面请求，重定向到登录页
            response.sendRedirect("/login.html");
            return false;
        }

        return true;
    }
}
